let fs = require('fs')
const utils = require('./utils')

function readFile(path) {
	return JSON.parse(fs.readFileSync(path, 'utf-8'))
}

let curd = {
	createId: () => {
		let date = new Date(), random = Math.ceil(Math.random() * 100000)
		return date.getTime() + '' + random
	},

	// 获取分页数据
	getPages: (filePath, params) => {
		let data = readFile(filePath)
		let fData = [
			...data.filter(it => {
				let flag = true

				for(let key in params) {
					if(params[key] !== null && it[key] && it[key].indexOf(params[key]) === -1) flag = false
				}

				return flag
			})
		]

		return utils.resultPageSuccess(params.pageNumber - 1, params.pageSize, fData)
	},

	// 批量删除数据
	deletes: ( filePath, ids ) => {
		let data = readFile(filePath)
		let list = data.filter(it => ids.indexOf(it.id) === -1)

		fs.writeFileSync(filePath, JSON.stringify( list ))

		return utils.resultSuccess( null )
	},

	// 更新
	update: ( filePath, params ) => {
		let data = readFile( filePath )
		let isUpdate = false

		data.forEach( ( it, index ) => {
			if( !isUpdate && it.id === params.id ) {
				isUpdate = true
				data[index] = Object.assign({}, data[index], params)
			}
		})

		fs.writeFileSync( filePath, JSON.stringify( data ) )

		return utils.resultSuccess( null )
	},

	// 新增
	add: (filePath, params) => {
		let data = readFile( filePath )
		params = Object.assign({}, params, {id: curd.createId()})

		data.push( params )

		fs.writeFileSync( filePath, JSON.stringify( data ) )

		return utils.resultSuccess( null )
	},

	queryById: ( filePath, id ) => {
		let data = readFile( filePath )
		let row = data.filter( it => it.id === id )[0]

		return utils.resultSuccess( row )
	}
}

module.exports = curd
